import router from "@/router";
import { userLoginUserStore } from "@/store/userStore";
import ACCESS_ENUM from "./accessEnum";
import checkAccess from "./checkAccess";

//进入页面前,进行权限校验
router.beforeEach(async (to, from, next) => {
  //获取当前登录用户
  const loginUserStore = userLoginUserStore();
  let loginUser = loginUserStore.loginUser;

  //如果之前没有尝试过登录,才自动登录
  if (!loginUser || !loginUser.userRole) {
    //加await是为了等待用户登录成功并获取到值后,再进行后续操作
    await loginUserStore.fetchLoginUser();
    loginUser = loginUserStore.loginUser;
  }
  //当前页面需要的权限
  const needAccess = (to.meta?.access as string) ?? ACCESS_ENUM.NOT_LOGIN;
  //要跳转到的页面必须登录
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    //如果没登录,跳转到登录页面
    if (!loginUser || !loginUser.userRole || loginUser.userRole === ACCESS_ENUM.NOT_LOGIN) {
      next(`/user/login?redirect=${to.fullPath}`);
    }
    //如果登录了,判断是否有权限,如果没有权限,跳转到无权限页面
    if (!checkAccess(loginUser, needAccess)) {
      next("/noAuth");
    }
    console.log("权限校验通过");
    next();
  } else {
    next();
  }
});
